function genNavBar(page_name) {
    var nav_bar = document.getElementById('navi_bar');
    var nav_list = [['Home', 'home'], ['Add Record', 'add_record'], ['Records', 'records'], ['Statistic', 'statistic'],
        ['Budget', 'budget'], ['Management', 'management']];
    var one_nav;
    nav_list.forEach(function(element) {
        one_nav = document.createElement('a');
        one_nav.innerHTML = element[0];
        one_nav.setAttribute('class', 'navi');
        one_nav.setAttribute('href', '/' + element[1]);
        if(page_name == element[1]) {
            one_nav.setAttribute('id', 'hight_light_nav_opt');
        }
        nav_bar.appendChild(one_nav);
    });
}

/**
 * 异步方式请求URL
 * @param {*} url 要请求的url
 * @param {*} onReturn200Callback 
 * @param {*} timeout_ms 
 */
function getUrlAsyn(url, onReturn200Callback, timeout_ms=2000) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.onreadystatechange = function() {
        if(xhr.readyState == 4) {
            if(xhr.status == 200) {
                onReturn200Callback(xhr.responseText);
            }
        }
    }    
    xhr.timeout = timeout_ms;
    xhr.send();
}

/**
 * 异步方式请求URL，用于失败时需要向用户明确提示的场景
 * @param {*} url           要请求的url
 * @param {*} call_back     请求结束后的回调函数，参数为一个字典，内容为{status, response}
 * @param {*} parse_json    是否对response进行json解析
 * @param {*} timeout_ms    超时时间，单位：毫秒，默认2000
 */
function getUrlAsyn2(url, call_back, parse_json=true, timeout_ms=2000) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.onreadystatechange = function() {
        if(xhr.readyState == 4) {
            call_back_arg = {'status':xhr.status};
            if(xhr.status == 200) {
                call_back_arg['response'] = xhr.responseText;
                if(parse_json == true) {
                    call_back_arg['response'] = JSON.parse(call_back_arg['response']);
                }
                call_back(call_back_arg);
            }
        }
    }
    xhr.ontimeout = function() {
        call_back_arg = {'status':999}
        call_back(call_back_arg);
    }
    xhr.timeout = timeout_ms;
    xhr.send();
}

/**
 * 判断字符串是否为合法的日期，格式为YYYY-MM-DD
 * 【注意】无法准确判断日期是否合法
 * @param {string} data_str 日期字符串
 * @return {boolean}
 */
function isLegalDateString(date_str) {
    nums = date_str.split('-')
    if(nums.length != 3) {
        return false;
    }
    year = Number(nums[0])
    month = Number(nums[1])
    day = Number(nums[2])
    if(year == NaN || year < 1970 || year > 2037
    || month == NaN || month < 1 || month > 12 || nums[1].length != 2
    || day == NaN || day < 1 || day > 31 || nums[2].length != 2) {
        return false
    }
    tmp = new Date(date_str)
    if(Date.parse(date_str) == NaN) {
        return false;
    }
    return true;
}

/**
 * 获取当前年月日时分字符串
 * @param {*} offset_ms 要获取的时间与当前时间的差值，单位为毫秒，0表示當前時間
 * @param {*} date_only 只需要年月日，不需要時分秒
 */
function getCurrentDateTimeString(offset_ms=0, date_only=false) {
    var ret = getDateTimeNumber(offset_ms);
    return genDateTimeString(ret.year, ret.month, ret.day, ret.hour, ret.minuate, date_only)
}

/**
 * 获取年月日时分的数值，返回一个字典
 * @param {int} offset_ms 要获取的时间与当前时间的差值，单位为毫秒，0表示當前時間
 */
function getDateTimeNumber(offset_ms=0) {
    var date;
    if(offset_ms == 0) {
        date = new Date();
    }
    else {
        var ts = Date.parse(new Date());
        ts += offset_ms;
        date = new Date(ts);
    }
    return {'year': date.getFullYear(),
    'month': date.getMonth() + 1,
    'day': date.getDate(),
    'hour': date.getHours(),
    'minuate': date.getMinutes()};
}

function genDateTimeString(year, month, day, hour, minuate, date_only=false) {
    if(month < 10) { month = '0' + month;}
    if(day < 10) { day = '0' + day;}
    if(hour < 10) { hour = '0' + hour;}
    if(minuate < 10) { minuate = '0' + minuate;}
    var ret = year + '-' + month + '-' + day;
    if(date_only == false) {
        ret += ' ' + hour + ':' + minuate;
    }
    return ret;    
}

// 清空元素中指定class的子元素
function clearSubElement(element, sub_ele_class) {
    var options =  element.getElementsByClassName(sub_ele_class);
    while(true) {
        opt = options.item(0);
        if(opt == null) {
            break;
        }
        element.removeChild(opt);
    }
}

// 清空元素中的所有子元素
function clearAllSubElement(parent_id) {
    var ele = document.getElementById(parent_id);
    ele.innerHTML = '';
}

// 向選項菜單中追加一個選項
function appendSelectorOption(select_ele, val, text, class_name) {
    opt = document.createElement('option')
    opt.text = text;
    opt.value = val;
    opt.className = class_name;
    select_ele.appendChild(opt);
}

// 根据crc_id更新account列表
function resetAccountListByCurrencyId(crc_id, currency_account) {
    // currency改变时，三个account的内容都要随之改变
    // 清空account的选项
    if(crc_id == 'null') {
        return;
    }
    var account_select = document.getElementById('account_select')
    var src_account_select = document.getElementById('src_account_select')
    var dst_account_select = document.getElementById('dst_account_select')
    clearSubElement(account_select, 'currency_select_opt');
    clearSubElement(src_account_select, 'src_account_select_opt');
    clearSubElement(dst_account_select, 'dst_account_select_opt');
    // 添加新的选项
    var account_list = currency_account[crc_id].account_list;
    account_list.forEach(function(info){
        appendSelectorOption(account_select, info.acnt_id, info.nameme, 'currency_select_opt');
        appendSelectorOption(src_account_select, info.acnt_id, info.nameme, 'src_account_select_opt');
        appendSelectorOption(dst_account_select, info.acnt_id, info.nameme, 'dst_account_select_opt');
    });
}

// 向一個div中添加echart的div
function addChartDiv(parentId, chartAreaId, charAreaClass, width, height) {
    var parent = document.getElementById(parentId);
    var newDiv = document.createElement('div');
    newDiv.setAttribute('id', chartAreaId);
    newDiv.setAttribute('class', charAreaClass);
    newDiv.style.width = width;
    newDiv.style.height = height;
    parent.appendChild(newDiv);
}

// 根据接口的返回值，显示对应的提示窗口
// ret为经过json解析后的接口返回内容
// 接口调用成功返回true，否则返回false
function showServiceReturnValue(ret) {
    if(ret.errno == 0) {
        alert('successed~');
        return true;
    }
    else {
        text = 'errno:' + ret.errno + ' message:' + ret.message;
        if('data' in ret) {
            text += '\ndetail: ' + JSON.stringify(ret.data);
        }
        alert(text);
    }
    return false;
}


/**
 * 把sidebar_id對應的item設置為高亮的樣式
 * 原有的高亮item回復原樣
 * 會修改g_current_sidebar_item_id這個全局變量
 */ 
function setHighLightSidebarItem(sidebar_id) {
    var old_element = document.getElementById(g_current_sidebar_item_id);
    var new_element = document.getElementById(sidebar_id);
    old_element.style.borderRadius = '';
    old_element.style.backgroundColor = '';
    old_element.style.disable = 'false';
    new_element.style.borderRadius = '20px';
    new_element.style.backgroundColor = 'gold';
    new_element.style.disable = 'true';
    g_current_sidebar_item_id = sidebar_id;
}

function genTimeRangeQuickButton(buttons_root, begin_time_textarea_id, end_time_textarea_id) {
    buttons = document.getElementById(buttons_root);
    buttons.style.paddingTop = '12px';
    buttons.innerHTML = '\
        <button onclick="trqb_today(\'' + begin_time_textarea_id + '\',\'' + end_time_textarea_id + '\')">今天</button>\
        <button onclick="trqb_this_month(\'' + begin_time_textarea_id + '\',\'' + end_time_textarea_id + '\')">本月</button>\
        <button onclick="trqb_this_year(\'' + begin_time_textarea_id + '\',\'' + end_time_textarea_id + '\')">本年</button>\
        <button onclick="trqb_one_week(\'' + begin_time_textarea_id + '\',\'' + end_time_textarea_id + '\')">一周内</button>\
        <button onclick="trqb_one_month(\'' + begin_time_textarea_id + '\',\'' + end_time_textarea_id + '\')">一月内</button>\
        <button onclick="trqb_one_year(\'' + begin_time_textarea_id + '\',\'' + end_time_textarea_id + '\')">一年内</button>\
        <button onclick="trqb_all(\'' + begin_time_textarea_id + '\',\'' + end_time_textarea_id + '\')">全部</button>';

}

// trqb = time range quick button
function trqb_today(begin_time_textarea_id, end_time_textarea_id) {
    ret = getDateTimeNumber();
    begin_time = genDateTimeString(ret.year, ret.month, ret.day, 0, 0, true);
    end_time = genDateTimeString(ret.year, ret.month, ret.day, 23, 59, true);
    document.getElementById(begin_time_textarea_id).value = begin_time;
    document.getElementById(end_time_textarea_id).value = end_time;
}

function trqb_this_month(begin_time_textarea_id, end_time_textarea_id) {
    ret = getDateTimeNumber();
    begin_time = genDateTimeString(ret.year, ret.month, 1, 0, 0, true);
    end_time = genDateTimeString(ret.year, ret.month, ret.day, 23, 59, true);
    document.getElementById(begin_time_textarea_id).value = begin_time;
    document.getElementById(end_time_textarea_id).value = end_time;
}

function trqb_this_year(begin_time_textarea_id, end_time_textarea_id) {
    ret = getDateTimeNumber();
    begin_time = genDateTimeString(ret.year, 1, 1, 0, 0, true);
    end_time = genDateTimeString(ret.year, ret.month, ret.day, 23, 59, true);
    document.getElementById(begin_time_textarea_id).value = begin_time;
    document.getElementById(end_time_textarea_id).value = end_time;
}

function trqb_one_week(begin_time_textarea_id, end_time_textarea_id) {
    begin_time = getCurrentDateTimeString(-7*24*3600*1000, true);
    end_time = getCurrentDateTimeString(0, true);
    document.getElementById(begin_time_textarea_id).value = begin_time;
    document.getElementById(end_time_textarea_id).value = end_time;
}

function trqb_one_month(begin_time_textarea_id, end_time_textarea_id) {
    begin_time = getCurrentDateTimeString(-30*24*3600*1000, true);
    end_time = getCurrentDateTimeString(0, true);
    document.getElementById(begin_time_textarea_id).value = begin_time;
    document.getElementById(end_time_textarea_id).value = end_time;
}

function trqb_one_year(begin_time_textarea_id, end_time_textarea_id) {
    begin_time = getCurrentDateTimeString(-365*24*3600*1000, true);
    end_time = getCurrentDateTimeString(0, true);
    document.getElementById(begin_time_textarea_id).value = begin_time;
    document.getElementById(end_time_textarea_id).value = end_time;
}

function trqb_all(begin_time_textarea_id, end_time_textarea_id) {
    begin_time = genDateTimeString(2000, 1, 1, 0, 0, true);
    end_time = genDateTimeString(2037, 12, 31, 0, 0, true);
    document.getElementById(begin_time_textarea_id).value = begin_time;
    document.getElementById(end_time_textarea_id).value = end_time;
}

